#!/bin/bash

prog=$(basename $0)
thisfile=$(readlink -f "$0")
thisdir=$(dirname "$thisfile")
HALFILE="$thisdir"/help.hal

cd ;# so user can use halcmd 'save' to create a file

function popup () {
  msg="$*"
  wish <<EOF &
  wm withdraw .
  tk_messageBox \
    -title "$prog" \
    -message "$msg" \
    -icon error \
    -type ok
  destroy .
EOF
} ;# popup


[ X"$TERM" = Xdumb ] && TERM=xterm
[ -x "$(which $COLORTERM)" ] && TERM=$COLORTERM
[ -z $TERM ] && TERM=xterm

# wip: xterm is well-behaved, some other terminals are not
# for now: force to xterm
TERM=xterm

REALTIME=$(linuxcnc_var REALTIME)
# make sure TERM uses the expected halrun (rip or install)
HALRUN=$(which halrun)

if [ ! -z "$debug" ] ; then
  echo COLORTERM=$COLORTERM
  echo TERM=$TERM
  echo HALRUN=$HALRUN
  echo REALTIME=$REALTIME
fi

if $REALTIME status >/dev/null ; then
  msg="$prog: LinuxCNC is active"
  echo "$msg"
  popup "$msg"
  exit 1
fi


# terminate any other halrun instance:
$HALRUN -U >/dev/null 2>&1

if [ X"$TERM" = Xxterm ] ; then
  $TERM -geometry 80x40 \
        -sb \
        -fg black -bg ivory2 \
        -title "halrun (Use Ctrl-L-button, Ctrl_R-button for xterm options)" \
        -e "echo Working_Directory=$(pwd);echo; $HALRUN -I $HALFILE"
else
  $TERM -e "$HALRUN -I $HALFILE"
fi

# cleanup
halrun -U >/dev/null 2>&1
exit 0
